import React, {Component} from "react";
import Text from "antd/es/typography/Text";
import {Button, Icon, Modal, Table} from "antd";
import {inject, observer} from "mobx-react";


export default @inject('store') @observer
class Worker extends Component {
    columns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: '创建时间',
            dataIndex: 'CreatedAt',
            key: 'CreatedAt',
        },
        {
            title: '更新时间',
            dataIndex: 'UpdatedAt',
            key: 'UpdatedAt',
        },
        {
            title: '机器ID',
            dataIndex: 'machine_id',
            key: 'machine_id',
        },
        {
            title: '机器IP',
            dataIndex: 'machine.ip',
            key: 'machine_ip',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                switch (text) {
                    case 0:
                        return <Text>运行中</Text>;
                    case 1:
                        return <Text type={"warning"}>已暂停</Text>;
                    case 2:
                        return <Text type={"danger"}>已停止</Text>;
                    default:
                }
            }
        },
        {
            title: '任务管理',
            render: (item) => (
                <Button type={"primary"} size={"small"} onClick={() => (this.workerManage(item))}>管理</Button>
            )
        },
        {
            title: '操作',
            render: (item) => {
                switch (item.status) {
                    case 0 :
                        return <Button type={"danger"} size={"small"} style={{marginRight: 5}}
                                       onClick={() => this._pause(item)}>暂停</Button>;
                    case 1:
                        return <Button type={"primary"} size={"small"} style={{marginRight: 5}}
                                       onClick={() => this._begin(item)}>开始</Button>;
                    case 2:
                        return ;
                    default:
                }

            }

        },
    ];

    settingColumns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: 'Host',
            dataIndex: 'host',
            key: 'host',
        },
        {
            title: '任务ID',
            dataIndex: 'seed_id',
            key: 'seed_id',
        },
        {
            title: '任务名',
            dataIndex: 'seed.name',
            key: 'name',
        },
        {
            title: '起始链接',
            dataIndex: 'seed.url',
            key: 'url',
        },
        {
            title: '操作',
            render: (item) => (
                <Button type={"danger"} size={"small"} onClick={() => this._bindWorkerCancel(item)}>解绑</Button>)
        },
    ];

    seedColumns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '链接',
            dataIndex: 'url',
            key: 'url',
        },
        {
            title: '解析方法名',
            dataIndex: 'function_name',
            key: 'function_name',
        },
    ];

    limit = 5;

    constructor(props) {
        super(props);

        this.state = {
            workers: [],
            current: 0,
            count: 0,

            selectedWorker: null,
            settingsVisible: false,
            settings: [],
            settingCurrent: 0,
            settingCount: 0,

            bindWorkerVisible: false,
            seeds: [],
            selectedSeed: null,
            seedsCurrent: 0,
            seedsCount: 0,
        }
    }

    componentDidMount() {
        this._getWorkers(0);
    }

    _getWorkers(offset) {
        window.$http.postForm("/worker/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({workers: res.workers, count: res.count});
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    workerManage(item) {
        this.setState({settingsVisible: true, selectedWorker: item});
        this._getSettings(item, 0);
    }

    _getSettings(item, offset) {
        window.$http.postForm("/nsq/gets/worker", {
            offset: offset,
            limit: this.limit,
            worker_id: item.ID
        }).then(res => {
            if (res.status === 10000) {
                this.setState({settings: res.settings, settingCount: res.count});
                console.log("settings", res.settings);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    getSeeds() {
        this._getSeeds(0);
        this.setState({bindWorkerVisible: true});
    }

    _getSeeds(offset) {
        window.$http.postForm("/seed/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({seeds: res.seeds, seedsCount: res.count});
                console.log("settings", res.settings);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    _bindWorker() {
        window.$http.postForm("/worker/bind", {
            worker_id: this.state.selectedWorker.ID,
            seed_id: this.state.selectedSeed.ID,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({bindWorkerVisible: false});
                // window.$message.success(res);
                // this.setState({seeds: res.seeds, count: res.count});
                console.log("setting", res.setting);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
        this._getSettings(this.state.selectedWorker, 0);
    }

    _bindWorkerCancel(item) {
        window.$http.postForm("/worker/bindCancel", {
            setting_id: item.ID,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("删除成功");
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
        this._getSettings(this.state.selectedWorker, 0);
    }

    _pause(item) {
        window.$http.postForm("/worker/pause", {
            worker_id: item.ID,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("暂停成功");
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
        this._getWorkers((this.state.current - 1) * this.limit);
    }

    _begin(item) {
        window.$http.postForm("/worker/begin", {
            worker_id: item.ID,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("启动成功");
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
        this._getWorkers((this.state.current - 1) * this.limit);
    }

    render() {
        return <>
            <Table rowKey={record => record.id}
                   pagination={{
                       total: this.state.count,
                       current: this.state.current,
                       pageSize: this.limit,
                       onChange: (page) => {
                           this.setState({current: page});
                           this._getWorkers((page - 1) * this.limit);
                       }
                   }}
                   columns={this.columns} dataSource={this.state.workers}/>
            {
                this.state.settingsVisible ?
                    <Modal title={'绑定任务'}
                           visible={this.state.settingsVisible} footer={null} width={'90%'} maskClosable={false}
                           onCancel={() => this.setState({settingsVisible: false, selectedWorker: null})}>
                        <Button type={"primary"} style={{marginLeft: 10, marginBottom: 5}}
                                onClick={() => this.getSeeds()}><Icon type={"plus"}/>绑定任务</Button>
                        <Table rowKey={record => record.id}
                               pagination={{
                                   total: this.state.settingCount,
                                   current: this.state.settingCurrent,
                                   pageSize: this.limit,
                                   onChange: (page) => {
                                       this.setState({settingCurrent: page});
                                       this._getSettings(this.state.selectedWorker, (page - 1) * this.limit);
                                   }
                               }}
                               columns={this.settingColumns} dataSource={this.state.settings} footer={null}/>
                        {
                            this.state.bindWorkerVisible ?
                                <Modal visible={this.state.bindWorkerVisible}
                                       width={1000}
                                       closable={false}
                                       onOk={() => this._bindWorker()}
                                       onCancel={() => this.setState({bindWorkerVisible: false})}>
                                    {/*todo: 添加选择功能*/}
                                    <Table rowKey={record => record.id}
                                           columns={this.seedColumns} dataSource={this.state.seeds}
                                           pagination={{
                                               total: this.state.seedsCount,
                                               current: this.state.seedsCurrent,
                                               pageSize: this.limit,
                                               onChange: (page) => {
                                                   this.setState({seedsCurrent: page});
                                                   this._getSeeds(this.state.selectedSeed, (page - 1) * this.limit);
                                               }
                                           }}
                                           rowSelection={{
                                               type: 'radio',
                                               onChange: (selectedRowsKey, selectedRows) => {
                                                   this.setState({
                                                       selectedSeed: selectedRows[0],
                                                   });
                                               },
                                           }}/>
                                </Modal> : null
                        }
                    </Modal> : null
            }

        </>
    }
}